﻿using System;
using System.Workflow.Runtime;

namespace TfsAlert.Core
{
    /// <summary>
    /// 
    /// </summary>
    public static class WorkflowFactory
    {
        private static WorkflowRuntime _workflowRuntime;
        private static object _syncRoot = new object();

        /// <summary>
        /// 
        /// </summary>
        /// <returns>Initalized WorkflowRuntime</returns>
        public static WorkflowRuntime GetWorkflowRuntime()
        {
            lock ( _syncRoot )
            {
                //Does the instance already exist?
                if ( null == _workflowRuntime )
                {
                    AppDomain.CurrentDomain.ProcessExit += new EventHandler( terminateWorkflowRuntime );
                    AppDomain.CurrentDomain.DomainUnload += new EventHandler( terminateWorkflowRuntime );

                    //TODO @CPS we will need to add the config file here so the services get loaded
                    _workflowRuntime = new WorkflowRuntime( );
                    _workflowRuntime.StartRuntime();
                }

                return _workflowRuntime;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void terminateWorkflowRuntime( object sender, EventArgs e )
        {
            if ( null != _workflowRuntime )
            {
                if ( _workflowRuntime.IsStarted )
                {
                    try
                    {
                        _workflowRuntime.StopRuntime();
                    }
                    catch ( ObjectDisposedException )
                    {
                        // already disposed
                    }
                }
            }
        }
    }
}
